package controllers

import (
	"encoding/json"
	"time"

	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"qkcoupon/utils"

	"sync"

	log "github.com/cihub/seelog"
)

type CreateExchangeController struct {
	URLSignController
}

var (
	mutex sync.Mutex
)

/*
 *@note  验证请求参数
 *@return (string, int64): (推荐者ID, 错误码)
 */
func (p *CreateExchangeController) verification() (string, uint) {
	errCode := errorcode.EC_GL_SUCCESS
	uid := ""
	for {
		uid = p.GetString("uid")
		if uid == "" {
			log.Warn("uid==''")
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		break
	}
	return uid, errCode
}

/*
 *@note 请求数据转换为服务端数据
 *@return (优惠码信息,优惠码兑换规则列表,错误码)
 */
func (p *CreateExchangeController) parseReq(req *models.PSQkCouponExchangeCreateReq) (*models.PSQkCouponExchangeInfo, *models.PSQkCouponExchangeRuleList, uint) {
	info := &models.PSQkCouponExchangeInfo{}
	if !utils.CheckExchangeText(req.Text) {
		log.Debugf("check fial")
		return info, nil, errorcode.EC_GL_INVALID_URL_PARAMS
	}
	if req.StartTick <= 0 || req.EndTick <= time.Now().Unix() {
		log.Debugf("check fial")
		return info, nil, errorcode.EC_GL_INVALID_URL_PARAMS
	}
	info.Bid = req.Bid
	info.Text = req.Text
	info.UserLimit = req.UserLimit
	info.CouponLimit = req.CouponLimit
	info.NewUserOnly = req.NewUserOnly
	info.StartTick = req.StartTick
	info.EndTick = req.EndTick

	ruleErr := p.checkRule(req.CouponRules)
	if ruleErr != errorcode.EC_GL_SUCCESS {
		return info, nil, ruleErr
	}
	rules := req.CouponRules
	return info, rules, errorcode.EC_GL_SUCCESS
}

// 用于校验优惠卷创建规则，防止数据库里存放错误数据
func (p *CreateExchangeController) checkRule(rules *models.PSQkCouponExchangeRuleList) uint {
	for _, rule := range rules.List {
		if rule.Discount < 0 || rule.MaxDiscount < 0 || rule.Sum < 0 {
			log.Debugf("check fial")
			return errorcode.EC_GL_INVALID_URL_PARAMS
		}
		if !utils.CheckCType(rule.Ctype) {
			log.Debugf("check fial")
			return errorcode.EC_GL_INVALID_URL_PARAMS
		}
		if !utils.CheckWashMode(rule.Lmode) {
			log.Debugf("check fial")
			return errorcode.EC_GL_INVALID_URL_PARAMS
		}
		// rwid保持传入状态
		// rule.Rwids = nil
		// if rule.Rwids!=""{
		// 	if utils.IsExistRwid(rule.Rwids){
		// 		return errorcode.EC_GL_INVALID_URL_PARAMS
		// 	}
		// }
	}
	return errorcode.EC_GL_SUCCESS
}

// CreateExchange 创建优惠码的接口
// @router /create [post]
func (p *CreateExchangeController) CreateExchange() {
	defer p.Output("CreateExchange")

	// 为了防止优惠码冲突，全局上锁
	mutex.Lock()
	defer mutex.Unlock()

	data := p.Ctx.Input.RequestBody
	if len(data) == 0 {
		log.Warn("len(data)==0")
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	log.Debug(string(data))

	req := &models.PSQkCouponExchangeCreateReq{}
	err := json.Unmarshal(data, req)
	if err != nil {
		log.Warnf("%s", err.Error())
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		return
	}

	// _, errCode := p.verification()
	// if errCode != errorcode.EC_GL_SUCCESS {
	// 	p.Resp["code"] = errCode
	// 	return
	// }

	info, rules, parseErr := p.parseReq(req)
	if parseErr != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = parseErr
		return
	}

	ok, checkErr := db.CheckExchangeCodeAddable(info.Text, info.StartTick)
	if checkErr != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}
	if ok {
		p.Resp["code"] = errorcode.EC_QKCOUPON_DUPLICATE_EXHCANGE_TEXT
		return
	}

	// 创建优惠码信息
	exchangeCode, err := db.CreateExchangeInfo(info)
	if err != nil {
		p.Resp["code"] = errorcode.EC_GL_EXEC_SQL_FAIL
		return
	}

	// 创建优惠码兑换规则
	err2 := db.CreateExchangeRules(exchangeCode, rules)
	if err2 != nil {
		p.Resp["code"] = errorcode.EC_GL_EXEC_SQL_FAIL
		return
	}

	p.Resp["code"] = errorcode.EC_GL_SUCCESS
}
